﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PanGu;
using Models;
using Lucene.Net;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.QueryParsers;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Store;
using System.IO;
namespace LuceneNetSearch
{
    public class LuceneSearch
    {
        public IList<BlogInfo> BlogSearch(string keyWords)
        {
            if (string.IsNullOrEmpty(keyWords))
            {
                return null;
            }
            string strDir = System.Configuration.ConfigurationManager.AppSettings["indexDirectory"];
            if (string.IsNullOrEmpty(strDir))
            {
                throw new Exception("指定的目录不能为空");
            }

            if (!IndexReader.IndexExists(strDir))
            {
                throw new Exception("指定的目录不是索引目录");
            }
            if (IndexReader.IsLocked(strDir))
            {
                DirectoryInfo dirInfo = new DirectoryInfo(strDir);
                Lucene.Net.Store.Directory dir = FSDirectory.Open(dirInfo);
                IndexReader.Unlock(dir);
            }
            IndexSearcher searcher = new IndexSearcher(FSDirectory.Open(new System.IO.DirectoryInfo(strDir)), false);

            MultiFieldQueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, new string[] { "title", "content" }, new PanGuAnalyzer());
            //   QueryParser parser = new QueryParser(keyWords, new PanGuAnalyzer());
            IList<BlogInfo> blogList = new List<BlogInfo>();
            Query query = parser.Parse(keyWords);
            Hits hits = searcher.Search(query);
            hits.debugCheckedForDeletions = true;
            for (int i = 0; i < hits.Length(); i++)
            {
                Document document = hits.Doc(i);
                BlogInfo blogInfo = new BlogInfo();
                blogInfo.AuthorID = Convert.ToInt32(string.IsNullOrEmpty(document.Get("authorID")) ? "0" : document.Get("authorID"));
                blogInfo.BlogContent = document.Get("content");
                blogInfo.LinkUrl = document.Get("linkUrl");
                blogInfo.Title = document.Get("title");
                blogList.Add(blogInfo);
            }
            searcher.Close();

            return blogList;
        }



    }
}
